/**
 *  非对称加密、解密类
 * */
import sm2M from 'miniprogram-sm-crypto'
const sm2 = sm2M.sm2
const cipherMode = 1 // 1 - C1C3C2，0 - C1C2C3，默认为1

// 加密
export const sm2Enc = (word, pubKey) => {
  const encryptData = sm2.doEncrypt(word, pubKey, cipherMode, { hash: true, der: true })
  return encryptData
}

// 解密
export const sm2Dec = (word, privateKey) => {
  const decryptData = sm2.doDecrypt(word, privateKey, cipherMode, { hash: true, der: true }) // 解密结果
  return decryptData
}

// 签名
export const sm2Signature = (word, privateKey) => {
  const signStr = sm2.doSignature(word, privateKey, { hash: true, der: true }) // 解密结果
  return signStr
}

// 验签
export const sm2Verify = (word, signStr, pubKey) => {
  try {
    const result = sm2.doVerifySignature(word, signStr, pubKey, { hash: true, der: true })
    return result
  } catch (e) {
    console.log(e.name + ':' + e.message)
  }
}

// 生成密钥
export const sm2GenKey = () => {
  const keypair = sm2.generateKeyPairHex()
  return {
    priKey: keypair.privateKey,
    pubKey: keypair.publicKey
  }
}
